package com.naiterui.ehp.bs.agent.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.Sets;
import com.naiterui.ehp.bs.agent.repository.IAsProviceCountRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.naiterui.ehp.bp.bo.agent.ProvinceItemBO;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bs.agent.entity.AgAgentArea;
import com.naiterui.ehp.bs.agent.entity.AgArea;
import com.naiterui.ehp.bs.agent.feign.ICmsapiFeignClient;
import com.naiterui.ehp.bs.agent.repository.IAgAgentAreaRepository;
import com.naiterui.ehp.bs.agent.repository.IAgAgentCustomRepository;
import com.naiterui.ehp.bs.agent.repository.IAgAreaRepository;
import com.naiterui.ehp.bs.agent.repository.IAsAreaCountRepository;
import com.naiterui.ehp.bs.agent.service.IAreaService;
import com.naiterui.ehp.bs.agent.vo.AreaInfoVO;
import com.naiterui.ehp.bs.agent.vo.ProvinceItemVO;
import com.naiterui.ehp.bs.agent.vo.TreeDataVO;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yiren
 * @since 2022/2/16
 */
@Slf4j
@Service
public class AreaServiceImpl implements IAreaService {
	@Autowired
	private IAgAreaRepository agAreaRepository;
	@Autowired
	private IAgAgentAreaRepository agAgentAreaRepository;
	@Autowired
	private IAgAgentCustomRepository agentCustomRepository;
    @Autowired
    private IAsAreaCountRepository asAreaCountRepository;
    @Autowired
    private ICmsapiFeignClient cmsapiFeignClient;
	@Autowired
	private IAsProviceCountRepository asProviceCountRepository;

	@Override
	public List<TreeDataVO> findTreeData() {
		Iterable<AgArea> dbList = agAreaRepository.findAll();
		// 最终返回的数据
		List<TreeDataVO> resultList = new ArrayList<>();
		Map<Long, TreeDataVO> responseMap = new HashMap<>();
		for (AgArea source : dbList) {
			TreeDataVO response = TreeDataVO.of(source.getId(), source.getAreaName());
			responseMap.put(response.getId(), response);
			if (source.getParentId() != null && source.getParentId() == 0){
				// 顶级
				resultList.add(response);
			}
		}
		for (AgArea source : dbList) {
			if (source.getParentId()==null){
				continue;
			}
			TreeDataVO parentResponse = responseMap.get(source.getParentId());
			if (parentResponse != null) {
				if(parentResponse.getChild()==null){
					parentResponse.setChild(new ArrayList<>());
				}
				parentResponse.getChild().add(responseMap.get(source.getId()));
			}
		}

		return resultList.stream().filter(a -> a.getChild() != null && a.getChild().size() > 0).collect(Collectors.toList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void changeArea(Long agentId, Long areaId) {
		List<AgAgentArea> dbAgentAreaList =
				agAgentAreaRepository.findByAgentIdAndTitleTypeOrderById(agentId, AgAgentArea.TITLE_TYPE_MANAGE);
		for (AgAgentArea item : dbAgentAreaList) {
			if (areaId.equals(item.getAreaId())){
				item.setAreaActive(AgAgentArea.AREA_ACTIVE_YSE);
			}else{
				item.setAreaActive(AgAgentArea.AREA_ACTIVE_NO);
			}
			agAgentAreaRepository.saveOrUpdate(item);
		}
	}
	private String[] getStartAndEndDate(String year, String month){
		String[] dates = new String[2];
		if (StringUtils.isAllEmpty(year, month)){
			dates[0] = "2022-01-01";
			dates[1] = DateUtil.formatDate(DateUtil.addDays(new Date(), 1), DateUtil.DATE_FORMAT);
		}else if (StringUtils.isEmpty(month)){
			dates[0] = year + "-01-01";
			dates[1] = year + "-12-32";
		}else{
			dates[0] = year +"-"+ month + "-01";
			dates[1] = year +"-"+ month + "-32";
		}
		return dates;
	}
	@Override
	public AreaInfoVO getAreaInfo(Long agentId, String year, String month) throws BusinessException {
        AgAgentArea dbActiveAgentArea = getManageArea(agentId);
		AgArea dbActiveArea = agAreaRepository.get(dbActiveAgentArea.getAreaId());
		String[] startAndEndDate = getStartAndEndDate(year, month);
		AreaInfoVO infoVO = new AreaInfoVO();
		infoVO.setAreaName(dbActiveArea.getAreaName());
		infoVO.setAreaLev(dbActiveArea.getAreaLev());
		List<Long> manageAreaIdList = new ArrayList<>();
		manageAreaIdList.add(dbActiveArea.getId());

		if (dbActiveArea.getAreaLev() == AgArea.AREA_LEV_REGION) {
			List<AgArea> provinceAreaIdList = agAreaRepository.findByParentId(dbActiveArea.getId());
			provinceAreaIdList.forEach(s -> manageAreaIdList.add(s.getId()));
		}
		List<Object[]> resultList = asAreaCountRepository.getSummaryByProviceAreaId(manageAreaIdList, startAndEndDate[0], startAndEndDate[1]);
		if (resultList != null && resultList.size() > 0) {
			Object[] item = resultList.get(0);
			//infoVO.setAgentTotal(item[0] == null ? 0 : Integer.valueOf(item[0].toString()));
			infoVO.setPrescriptionTotal(item[1] == null ? 0 : Integer.valueOf(item[1].toString()));
			infoVO.setDrugAmount(item[2] == null ? 0 : Integer.valueOf(item[2].toString()));
			infoVO.setInviteCustomTotal(item[3] == null ? 0 : Integer.valueOf(item[3].toString()));
		}
		// 查询截至今天凌晨总成员数
		String endTime = DateUtil.formatDate(DateUtil.getStartTime(null).getTime(), DateUtil.DATE_FORMAT);
		long agentTotal = agAgentAreaRepository.countAgentTotal(manageAreaIdList, endTime);
		infoVO.setAgentTotal(agentTotal);
		return infoVO;
	}

    @Override
    public List<ProvinceItemVO> findProvinceList(Long agentId, String year, String month)
        throws BusinessException {
        AgAgentArea area = getManageArea(agentId);
        List<AgArea> areaList = agAreaRepository.findByParentId(area.getAreaId());
        if (CollUtil.isEmpty(areaList)) {
            return Collections.emptyList();
        }
        List<Long> proviceAreaIdList = areaList.stream().map(AgArea::getId).collect(Collectors.toList());
        List<ProvinceItemBO> proviceTotal = cmsapiFeignClient.getProviceTotal(area.getAreaId(),
            proviceAreaIdList.stream().map(p -> p.toString()).collect(Collectors.joining(",")), year, month);
        Map<Long, ProvinceItemBO> map =
            proviceTotal.stream().collect(Collectors.toMap(ProvinceItemBO::getProviceAreaId, a -> a));
        return areaList.stream().map(a -> {
            ProvinceItemVO itemVO = new ProvinceItemVO();
            itemVO.setAreaId(a.getId());
            itemVO.setAreaName(a.getAreaName());
            ProvinceItemBO bo = map.get(a.getId());
            if (bo == null) {
                itemVO.setPrescriptionTotal(0);
                itemVO.setDrugAmount(0L);
                itemVO.setInviteCustomTotal(0);
            } else {
                itemVO.setPrescriptionTotal(bo.getPrescriptionTotal());
                itemVO.setDrugAmount(bo.getDrugAmount());
                itemVO.setInviteCustomTotal(bo.getInviteCustomTotal());
            }
            return itemVO;
        }).collect(Collectors.toList());
    }

	/**
	 * 查询经纪人当前激活的经理区域
	 * @param agentId
	 * @return
	 * @throws BusinessException
	 */
    private AgAgentArea getManageArea(Long agentId) throws BusinessException {

        List<AgAgentArea> dbAgentAreaList =
            agAgentAreaRepository.findByAgentIdAndTitleTypeOrderById(agentId, AgAgentArea.TITLE_TYPE_MANAGE);
        if (dbAgentAreaList.size() == 0) {
            throw new BusinessException(BaseExceptionCodes.PARAM_ERROR, "当前用户不是经理");
        }
        AgAgentArea activeItem = null;
        for (AgAgentArea item : dbAgentAreaList) {
            if (item.getAreaActive() != null && item.getAreaActive() == AgAgentArea.AREA_ACTIVE_YSE) {
                activeItem = item;
                break;
            }
        }
        if (activeItem == null) {
            activeItem = dbAgentAreaList.get(0);
        }
        return activeItem;
    }
}
